package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"goweb/models"
)

type GetSessionController struct {
	CommonController
}

/**
 *获取session
 */
func (this *GetSessionController) ISession() {
	uinfo := this.GetSession("uinfo")
	resp := make(map[string]interface{})
	defer this.RetData(resp)
	if uinfo != nil {
		resp["errno"] = models.RECODE_OK
		resp["errmsg"] = models.RecodeText(models.RECODE_OK)
		resp["data"] = uinfo
		return
	} else {
		resp["errno"] = models.RECODE_SESSIONERR
		resp["errmsg"] = models.RecodeText(models.RECODE_SESSIONERR)
		return
	}
}

/**
 *删除session
 */
func (this *GetSessionController) DSession() {
	this.DelSession("uinfo")
	resp := make(map[string]interface{})
	defer this.RetData(resp)
	uinfo := this.GetSession("uinfo")
	if uinfo != nil {
		resp["errno"] = models.RECODE_SESSIONERR
		resp["errmsg"] = models.RecodeText(models.RECODE_SESSIONERR)
		return
	} else {
		resp["errno"] = models.RECODE_OK
		resp["errmsg"] = models.RecodeText(models.RECODE_OK)
		return
	}
}

/**
 *用户登陆
 */
func (this *GetSessionController) Login() {
	param := make(map[string]interface{})
	resp := make(map[string]interface{})
	json.Unmarshal(this.Ctx.Input.RequestBody, &param)
	defer this.RetData(resp)

	if param["username"] == nil || param["password"] == nil {
		resp["errno"] = models.RECODE_DATAERR
		resp["errmsg"] = models.RecodeText(models.RECODE_DATAERR)
		return
	}

	o := orm.NewOrm()
	user := models.User{Name: param["username"].(string)}

	qs := o.QueryTable("user")
	err := qs.Filter("name", param["username"]).One(&user)
	fmt.Println(err, param["username"])
	if err != nil {
		resp["errno"] = models.RECODE_DATAERR
		resp["errmsg"] = models.RecodeText(models.RECODE_DATAERR)
		return
	}
	if user.Password_hash != param["password"] {
		resp["errno"] = models.RECODE_DATAERR
		resp["errmsg"] = models.RecodeText(models.RECODE_DATAERR)
		return
	}

	uinfo := make(map[string]interface{})
	uinfo["id"] = user.Id
	uinfo["name"] = user.Name
	this.SetSession("uinfo", uinfo)
	resp["errno"] = models.RECODE_OK
	resp["errmsg"] = models.RecodeText(models.RECODE_OK)
	return
}
